package com.blogsystem.controller;

import com.blogsystem.entity.Category;
import com.blogsystem.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
@RequestMapping("/api/categories")

public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    private static final Logger logger = LoggerFactory.getLogger(CategoryController.class);

    /**
     * 查询所有分类（用户/管理员均可）
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<List<Category>> listCategories() {
        try {
            List<Category> categories = categoryService.list();
            if (categories == null || categories.isEmpty()) {
                return ResponseEntity.noContent().build();
            }
            logger.info("查询分类列表: {}", categories);
            return ResponseEntity.ok(categories);
        } catch (Exception e) {
            logger.error("查询分类列表时发生错误", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @GetMapping("/name/{name}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Category> getCategoryByName(@PathVariable String name) {
        Category category = categoryService.getByName(name);
        if (category != null) {
            return ResponseEntity.ok(category);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

   /**
     * 新增分类（管理员）
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<String> addCategory(@RequestBody Category category) {
        boolean success = categoryService.save(category);
        if (success) {
            return ResponseEntity.ok("新增分类成功");
        } else {
            return ResponseEntity.status(500).body("新增分类失败");
        }
    }/**
     * 修改分类（管理员）
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<String> updateCategory(@PathVariable Integer id, @RequestBody Category category) {
        category.setCategoryId(id); // 设置分类ID
        boolean success = categoryService.updateById(category);
        if (success) {
            return ResponseEntity.ok("修改分类成功");
        } else {
            return ResponseEntity.status(500).body("修改分类失败");
        }
    }/**
     * 删除分类（管理员）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<String> deleteCategory(@PathVariable Integer id) {
        boolean success = categoryService.removeById(id);
        if (success) {
            return ResponseEntity.ok("删除分类成功");
        } else {
            return ResponseEntity.status(500).body("删除分类失败");
        }
    }
} 